/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool myfind(TreeNode* node,TreeNode* x)
    {
        if(node==nullptr)
            return false;

        return node==x
            ||myfind(node->left,x)
            ||myfind(node->right,x);
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==nullptr)
            return nullptr;
        
        if(p==root||q==root)
        {
            return root;
        }

        bool qinleft,qinright,pinleft,pinright;

        qinleft=myfind(root->left,q);
        qinright=myfind(root->right,q);
        pinleft=myfind(root->left,p);
        pinright=myfind(root->right,p);

        if(qinleft&&pinleft)
        {
            return lowestCommonAncestor(root->left,p,q);
        }
        else if(qinright&&pinright)
        {
            return lowestCommonAncestor(root->right,p,q);
        }
        else
        {
            return root;
        }
        return nullptr;
    }
};
